package com.ydles.system.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * 全局过滤器
 *
 * Ordered
 * GlobalFilter
 *
 * ip拦截
 * 危险操作日志打印
 *
 */
@Component //交由spring创建
public class IpFilter implements Ordered, GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //业务逻辑 -》ip黑名单拦截

        //拿到请求和响应，不就可以为所欲为了
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //远程地址
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostName = remoteAddress.getHostName();

        if (hostName.equals("1.1.1.1")){
            //拒绝访问
            response.setStatusCode(HttpStatus.FORBIDDEN);//响应码,看setStatusCode要什么
            return response.setComplete();
        }

        //放行 ， 看 chain.filter返回什么
        return chain.filter(exchange); //过滤器往后走

    }

    //指定过滤器顺序，越小越先执行
    @Override
    public int getOrder() {
        return 1;
    }
}
